//
//  AppController.m
//  MockupClient
//
//  Created by Christoph Eßer on 1/18/12.
//  Copyright 2012 __MyCompanyName__. All rights reserved.
//

#import "AppController.h"
#import "NetworkMessage.h"
#import "NetworkMessageCreator.h"
#import "NetworkingCenter.h"

@implementation AppController

- (id)initWithWindow:(NSWindow *)window
{
    self = [super initWithWindow:window];
    if (self) {
        // Initialization code here.
    }
    
    return self;
}

- (void)dealloc
{
    [super dealloc];
}

- (void)windowDidLoad
{
    [super windowDidLoad];
    // Implement this method to handle any initialization after your window controller's window has been loaded from its nib file.
}

-(void)incomingMessage:(NSNotification*)not {
    NetworkMessage *msg = (NetworkMessage*)[not object];
    NSLog(@"Incoming message %@, type: %d", msg, msg.type);
    
    if([msg.data isKindOfClass:[NSDictionary class]]) {
        NSLog(@"Data: %@", msg.data);
    }   
}

-(IBAction) connectAndLogin:(id)sender {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(incomingMessage:) name:NETWORKING_NOTIFICATION object:nil];

    
    [[NetworkingCenter defaultServer] openConnectionToServer];
    
    NetworkMessage *ntwrMsg = [NetworkMessageCreator loginMessageWith:[userNameField stringValue] role:[typeMatrix selectedRow] team:[teamNameField intValue]];
    [[NetworkingCenter defaultServer] sendMessage:ntwrMsg];
    
    [userNameField setEnabled:false];
    [teamNameField setEnabled:false];
    [typeMatrix setEnabled:false];
    
    //create a timer for sending location
    locationtimer = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(sendLocation:) userInfo:nil repeats:true];
    
}

- (IBAction)disconnect:(id)sender {
    if([[NetworkingCenter defaultServer] isRunning]) {
        [[NetworkingCenter defaultServer] closeConnectionToServer];
    }
    
    [userNameField setEnabled:true];
    [teamNameField setEnabled:true];
    [typeMatrix setEnabled:true];
    [locationtimer invalidate];
}

-(void) sendLocation:(NSTimer*) timer{
    //send the location to the server
    [[NetworkingCenter defaultServer] sendMessage:
     [NetworkMessageCreator locationMessageWithLatitude:[latitudeField doubleValue] 
                                              longitude:[longitudeField doubleValue]
                                               accuracy:[accuracyField doubleValue]]
     ];
}

@end
